<template>
  <div class="page-content">
    <div class="user-management">
      <div class="page-header">
        <div class="header-actions">
          <div 
            class="custom-upload-btn"
            @click="showCreateUserDialog"
          >
            <i class="el-icon-plus"></i>
            <span>新增用户</span>
          </div>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="user-list-container">
        <div v-if="userListLoading" class="loading-container">
          <div class="loading-spinner">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>
        </div>
        <div v-else class="table-container">
          <div class="table-header">
            <div class="header-cell id-col">ID</div>
            <div class="header-cell username-col">用户名</div>
            <div class="header-cell number-col">窗口数量</div>
            <div class="header-cell admin-col">管理员</div>
            <div class="header-cell time-col">创建时间</div>
            <div class="header-cell actions-col">操作</div>
          </div>
          <div class="table-body">
            <div v-if="userList.length === 0" class="empty-state">
              <div class="empty-icon">👥</div>
              <div class="empty-text">暂无用户数据</div>
              <div class="empty-desc">点击右上角"新增用户"按钮添加用户</div>
            </div>
            <div v-else v-for="user in userList" :key="user.id" class="table-row">
              <div class="cell id-col">{{ user.id }}</div>
              <div class="cell username-col">{{ user.username }}</div>
              <div class="cell number-col">{{ user.number }}</div>
              <div class="cell admin-col">
                <span :class="['admin-badge', user.is_admin ? 'admin' : 'normal']">
                  {{ user.is_admin ? '是' : '否' }}
                </span>
              </div>
              <div class="cell time-col">{{ formatDate(user.create_time) }}</div>
              <div class="cell actions-col">
                <div class="user-actions">
                  <button class="action-btn edit" @click="showEditUserDialog(user)">
                    编辑
                  </button>
                  <button class="action-btn reset" @click="showResetPasswordDialog(user)">
                    重置密码
                  </button>
                  <button 
                    class="action-btn delete" 
                    @click="handleDeleteUser(user)"
                    :disabled="user.id === userInfo.id"
                  >
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 创建用户模态框 -->
      <div v-if="showCreateUserDialogRef" class="modal-overlay" @click="closeCreateUserDialog">
        <div class="modal-container" @click.stop>
          <div class="modal-header">
            <h3>新增用户</h3>
            <button class="close-btn" @click="closeCreateUserDialog">×</button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label>用户名</label>
              <input 
                v-model="userForm.username" 
                type="text" 
                placeholder="请输入用户名（至少3个字符）"
                :disabled="userFormLoading"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>密码</label>
              <input 
                v-model="userForm.password" 
                type="password" 
                placeholder="请输入密码（至少6个字符）"
                :disabled="userFormLoading"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>窗口数量</label>
              <input 
                v-model.number="userForm.number" 
                type="number" 
                min="1" 
                max="50"
                :disabled="userFormLoading"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label class="switch-label">
                <span>管理员权限</span>
                <div class="switch-container">
                  <input 
                    v-model="userForm.is_admin" 
                    type="checkbox" 
                    :disabled="userFormLoading"
                    class="switch-input"
                  />
                  <div class="switch-slider"></div>
                </div>
              </label>
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn secondary" @click="closeCreateUserDialog" :disabled="userFormLoading">
              取消
            </button>
            <button class="btn primary" @click="handleCreateUser" :disabled="userFormLoading">
              <span v-if="userFormLoading" class="btn-spinner"></span>
              创建
            </button>
          </div>
        </div>
      </div>

      <!-- 编辑用户模态框 -->
      <div v-if="showEditUserDialogRef" class="modal-overlay" @click="closeEditUserDialog">
        <div class="modal-container" @click.stop>
          <div class="modal-header">
            <h3>编辑用户</h3>
            <button class="close-btn" @click="closeEditUserDialog">×</button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label>用户名</label>
              <input 
                v-model="editUserForm.username" 
                type="text" 
                placeholder="请输入用户名（至少3个字符）"
                :disabled="userFormLoading"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>窗口数量</label>
              <input 
                v-model.number="editUserForm.number" 
                type="number" 
                min="1" 
                max="50"
                :disabled="userFormLoading"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label class="switch-label">
                <span>管理员权限</span>
                <div class="switch-container">
                  <input 
                    v-model="editUserForm.is_admin" 
                    type="checkbox" 
                    :disabled="userFormLoading || (currentEditUser && currentEditUser.id === userInfo.id)"
                    class="switch-input"
                  />
                  <div class="switch-slider"></div>
                </div>
              </label>
              <div v-if="currentEditUser && currentEditUser.id === userInfo.id" class="form-help-text">
                不能修改自己的管理员权限
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn secondary" @click="closeEditUserDialog" :disabled="userFormLoading">
              取消
            </button>
            <button class="btn primary" @click="handleUpdateUser" :disabled="userFormLoading">
              <span v-if="userFormLoading" class="btn-spinner"></span>
              更新
            </button>
          </div>
        </div>
      </div>

      <!-- 重置密码模态框 -->
      <div v-if="showResetPasswordDialogRef" class="modal-overlay" @click="closeResetPasswordDialog">
        <div class="modal-container" @click.stop>
          <div class="modal-header">
            <h3>重置密码</h3>
            <button class="close-btn" @click="closeResetPasswordDialog">×</button>
          </div>
          <div class="modal-body">
            <div class="reset-password-info">
              <p>为用户 <strong>{{ currentEditUser?.username }}</strong> 重置密码</p>
            </div>
            <div class="form-group">
              <label>新密码</label>
              <input 
                v-model="resetPasswordForm.new_password" 
                type="password" 
                placeholder="请输入新密码（至少6个字符）"
                :disabled="userFormLoading"
                class="form-input"
              />
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn secondary" @click="closeResetPasswordDialog" :disabled="userFormLoading">
              取消
            </button>
            <button class="btn warning" @click="handleResetPassword" :disabled="userFormLoading">
              <span v-if="userFormLoading" class="btn-spinner"></span>
              重置密码
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import userAPI from '../api/users'

export default {
  name: 'UserManagement',
  setup() {
    const userInfo = ref({
      username: '',
      is_admin: false
    })

    // 用户列表相关
    const userList = ref([])
    const userListLoading = ref(false)

    // 对话框控制
    const showCreateUserDialogRef = ref(false)
    const showEditUserDialogRef = ref(false)
    const showResetPasswordDialogRef = ref(false)

    // 表单数据
    const userForm = ref({
      username: '',
      password: '',
      number: 1,
      is_admin: false
    })

    const editUserForm = ref({
      username: '',
      number: 1,
      is_admin: false
    })

    const resetPasswordForm = ref({
      new_password: ''
    })

    const currentEditUser = ref(null)
    const userFormLoading = ref(false)

    // 用户管理方法
    const loadUserList = async () => {
      userListLoading.value = true
      try {
        const response = await userAPI.getUserList()
        userList.value = response.data || []
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        userListLoading.value = false
      }
    }

    const showCreateUserDialog = () => {
      userForm.value = {
        username: '',
        password: '',
        number: 1,
        is_admin: false
      }
      showCreateUserDialogRef.value = true
    }

    const closeCreateUserDialog = () => {
      showCreateUserDialogRef.value = false
    }

    const showEditUserDialog = (user) => {
      if (!user) return
      currentEditUser.value = user
      editUserForm.value = {
        username: user.username,
        number: user.number,
        is_admin: user.is_admin
      }
      showEditUserDialogRef.value = true
    }

    const closeEditUserDialog = () => {
      showEditUserDialogRef.value = false
    }

    const showResetPasswordDialog = (user) => {
      if (!user) return
      currentEditUser.value = user
      resetPasswordForm.value = {
        new_password: ''
      }
      showResetPasswordDialogRef.value = true
    }

    const closeResetPasswordDialog = () => {
      showResetPasswordDialogRef.value = false
    }

    const handleCreateUser = async () => {
      userFormLoading.value = true
      try {
        await userAPI.createUser(userForm.value)
        ElMessage.success('用户创建成功')
        showCreateUserDialogRef.value = false
        await loadUserList()
      } catch (error) {
        console.error('创建用户失败:', error)
        ElMessage.error(error.response?.data?.error || '创建用户失败')
      } finally {
        userFormLoading.value = false
      }
    }

    const handleUpdateUser = async () => {
      userFormLoading.value = true
      try {
        await userAPI.updateUser(currentEditUser.value.id, editUserForm.value)
        ElMessage.success('用户更新成功')
        showEditUserDialogRef.value = false
        await loadUserList()
      } catch (error) {
        console.error('更新用户失败:', error)
        ElMessage.error(error.response?.data?.error || '更新用户失败')
      } finally {
        userFormLoading.value = false
      }
    }

    const handleResetPassword = async () => {
      userFormLoading.value = true
      try {
        await userAPI.resetUserPassword(currentEditUser.value.id, resetPasswordForm.value.new_password)
        ElMessage.success('密码重置成功')
        showResetPasswordDialogRef.value = false
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error(error.response?.data?.error || '重置密码失败')
      } finally {
        userFormLoading.value = false
      }
    }

    const handleDeleteUser = async (user) => {
      if (!user) {
        ElMessage.error('用户数据无效')
        return
      }
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${user.username || '未知用户'}" 吗？这将同时删除该用户的所有角色数据。`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await userAPI.deleteUser(user.id)
        ElMessage.success('用户删除成功')
        await loadUserList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          ElMessage.error(error.response?.data?.error || '删除用户失败')
        }
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) return '-'
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
      } catch (error) {
        console.error('日期格式化失败:', error)
        return '-'
      }
    }

    onMounted(async () => {
      // 获取当前用户信息
      const user = localStorage.getItem('user')
      if (user) {
        try {
          const parsedUser = JSON.parse(user)
          userInfo.value = {
            username: parsedUser.username || '',
            is_admin: parsedUser.is_admin || false,
            id: parsedUser.id,
            ...parsedUser
          }
        } catch (error) {
          console.error('解析用户信息失败:', error)
        }
      }
      await loadUserList()
    })

    return {
      userInfo,
      userList,
      userListLoading,
      showCreateUserDialogRef,
      showEditUserDialogRef,
      showResetPasswordDialogRef,
      userForm,
      editUserForm,
      resetPasswordForm,
      currentEditUser,
      userFormLoading,
      loadUserList,
      showCreateUserDialog,
      closeCreateUserDialog,
      showEditUserDialog,
      closeEditUserDialog,
      showResetPasswordDialog,
      closeResetPasswordDialog,
      handleCreateUser,
      handleUpdateUser,
      handleResetPassword,
      handleDeleteUser,
      formatDate
    }
  }
}
</script>

<style scoped>
.page-content {
  padding: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.user-management {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 32px;
  padding: 0 4px;
}

/* 自定义主要操作按钮样式 */
.custom-upload-btn {
  background: #409EFF;
  color: white;
  border: none;
  border-radius: 6px;
  width: 120px;
  height: 40px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.custom-upload-btn:hover {
  background: #66b1ff;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
}

.custom-upload-btn:active {
  background: #3a8ee6;
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.custom-upload-btn i {
  font-size: 14px;
  margin-right: 6px;
}

.custom-upload-btn span {
  font-size: 14px;
}

/* 用户列表容器 */
.user-list-container {
  flex: 1;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-top: 3px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-spinner p {
  margin: 0;
  color: #86868b;
  font-size: 16px;
}

/* 表格样式 */
.table-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: grid;
  grid-template-columns: 80px 1fr 120px 100px 180px 280px;
  background: #f8f9fa;
  padding: 16px 20px;
  font-weight: 600;
  color: #1d1d1f;
  font-size: 14px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  gap: 16px;
}

.table-body {
  flex: 1;
  overflow: auto;
}

.table-row {
  display: grid;
  grid-template-columns: 80px 1fr 120px 100px 180px 280px;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  align-items: center;
  transition: all 0.2s ease;
  gap: 16px;
}

.table-row:hover {
  background: rgba(0, 0, 0, 0.02);
}

.header-cell, .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.cell {
  color: #1d1d1f;
}

.admin-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.admin-badge.admin {
  background: rgba(52, 199, 89, 0.1);
  color: #34c759;
}

.admin-badge.normal {
  background: rgba(0, 0, 0, 0.05);
  color: #86868b;
}

.user-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  background: none;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 6px 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  font-weight: 500;
}

.action-btn.edit {
  color: #007aff;
  border-color: rgba(0, 122, 255, 0.2);
}

.action-btn.edit:hover {
  background: rgba(0, 122, 255, 0.1);
}

.action-btn.reset {
  color: #ff9500;
  border-color: rgba(255, 149, 0, 0.2);
}

.action-btn.reset:hover {
  background: rgba(255, 149, 0, 0.1);
}

.action-btn.delete {
  color: #ff3b30;
  border-color: rgba(255, 59, 48, 0.2);
}

.action-btn.delete:hover:not(:disabled) {
  background: rgba(255, 59, 48, 0.1);
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #86868b;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: #86868b;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.2s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.modal-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: hidden;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from { 
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to { 
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 0 24px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1d1d1f;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #86868b;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
}

.modal-body {
  padding: 0 24px;
  max-height: 60vh;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.2s ease;
  background: white;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
}

.form-input:disabled {
  background: #f5f5f7;
  color: #86868b;
}

/* 开关样式 */
.switch-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.switch-container {
  position: relative;
}

.switch-input {
  opacity: 0;
  width: 0;
  height: 0;
}

.switch-slider {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 30px;
  background: #e5e5ea;
  border-radius: 15px;
  transition: all 0.2s ease;
  cursor: pointer;
}

.switch-slider::before {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  width: 26px;
  height: 26px;
  background: white;
  border-radius: 50%;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.switch-input:checked + .switch-slider {
  background: #34c759;
}

.switch-input:checked + .switch-slider::before {
  transform: translateX(20px);
}

.switch-input:disabled + .switch-slider {
  opacity: 0.5;
  cursor: not-allowed;
}

.form-help-text {
  font-size: 12px;
  color: #86868b;
  margin-top: 8px;
}

.reset-password-info {
  margin-bottom: 20px;
  padding: 16px;
  background: rgba(0, 122, 255, 0.05);
  border: 1px solid rgba(0, 122, 255, 0.1);
  border-radius: 8px;
}

.reset-password-info p {
  margin: 0;
  color: #007aff;
  font-size: 14px;
}

.modal-footer {
  padding: 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn.secondary {
  background: #f5f5f7;
  color: #1d1d1f;
}

.btn.secondary:hover {
  background: #e5e5ea;
}

.btn.primary {
  background: #007aff;
  color: white;
}

.btn.primary:hover {
  background: #0056cc;
}

.btn.warning {
  background: #ff9500;
  color: white;
}

.btn.warning:hover {
  background: #cc7700;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-header,
  .table-row {
    grid-template-columns: 60px 1fr 80px 80px 120px 200px;
    gap: 8px;
  }
  
  .user-actions {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-btn {
    width: 100%;
    text-align: center;
  }
  
  .modal-container {
    width: 95%;
    margin: 20px;
  }
}

@media (max-width: 640px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .header-cell,
  .cell {
    padding: 8px 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }
  
  .header-cell:last-child,
  .cell:last-child {
    border-bottom: none;
  }
}
</style>
